package com.xxkj.drugtraceability.ui.doctoradviceback

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.xxhis.drugtraceability.base.BaseViewModel
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.net.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: zhoujingjin
 * created on: 2024/9/10 16:15
 * description:
 */
class DoctorAdviceBackViewModel(application: Application, private val repository: DoctorAdviceBackRepository):BaseViewModel(application) {
    var prescriptioninfo = mutableListOf<DoctorAdviceInfoBean>()
    var showList = mutableListOf<DrugInfoBean>()
    var baseUiModel = MutableLiveData<BaseUiModel<Boolean>>()
    var update = MutableLiveData<Boolean>()


    fun getSendBackList(barcode:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                //获取下面具体数据
                val resultQuery = repository.getSendBackList(
                    Gson().toJson(
                        TraceRequest(
                            barcode,
                            "2"
                        )
                    )
                )
                if (resultQuery is Result.Success) {
                    if (resultQuery.data.data.isNotEmpty()) {
                        prescriptioninfo=resultQuery.data.data.toMutableList()

                    }
                    update.postValue(true)
                    baseUiModel.postValue(BaseUiModel(showLoading = false))
                } else if (resultQuery is Result.Error) {
                    baseUiModel.postValue(
                        BaseUiModel(
                            showLoading = false,
                            showError = resultQuery.errorData ?: resultQuery.exception.message
                        )
                    )
                }
            }}
    }
    /**
     * 保存数据
     */
    fun finishScanBackDrugCode(finishRequest: FinishAdviceRequest, backItem: DoctorAdviceInfoBean){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                val result = repository.finishScanBackDrugCode(GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(finishRequest))
                if (result is Result.Success){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showSuccess = true))
                    prescriptioninfo.remove(backItem)
                    update.postValue(true)
                }else if (result is Result.Error){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                }
            }
        }
    }

}